from cas import CASClient
from django.conf import settings
from django.contrib.auth import get_user_model


def get_cas_client(server_url, service_url, version):
    return CASClient(
        server_url=server_url,
        service_url=service_url,
        version=version,
    )


class CASBackend:
    """CAS authentication backend"""

    def authenticate(self, request, ticket, service):
        """Verifies CAS ticket and gets or creates User object"""
        cas_server_url = settings.CAS_SERVER_URL
        cas_version = settings.CAS_VERSION
        client = get_cas_client(
            server_url=cas_server_url, service_url=service, version=cas_version
        )
        username, attributes, pgtiou = client.verify_ticket(ticket)

        if not attributes or not username:
            return None

        # NOTE: Support for custom user model.
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(username=username)
            return user
        except UserModel.DoesNotExist:
            user = UserModel.objects.create_user(username, password=None)
            return user

    def get_user(self, user_id):
        """Retrieve the user's entry in the User model if it exists"""
        UserModel = get_user_model()

        try:
            return UserModel.objects.get(pk=user_id)
        except UserModel.DoesNotExist:
            return None
